package com.itheima.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.*;
import com.itheima.youdianda.entity.RoleAdd;
import com.itheima.youdianda.entity.SysMenu;
import com.itheima.youdianda.entity.SysRole;
import com.itheima.youdianda.entity.SysRoleMenu;
import com.itheima.youdianda.mapper.SysRoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.service.SysMenuService;
import com.itheima.youdianda.service.SysRoleMenuService;
import com.itheima.youdianda.service.SysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 获取角色分页数据
     *
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @Override
    public RoleDto getRoleList(String page, String limit, String name) {
        Page<SysRole> pageInfo = new Page<>(Long.parseLong(page), Long.parseLong(limit));
        RoleDto roleDto = new RoleDto();
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), SysRole::getName, name);
        List<RoleDataDto> dataDtoList = new ArrayList<>();
        this.page(pageInfo, wrapper);
        for (SysRole record : pageInfo.getRecords()) {
            RoleDataDto roleDataDto = new RoleDataDto();
            BeanUtils.copyProperties(record, roleDataDto);
            roleDataDto.setRole_id(record.getId());
            LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRoleMenu::getRole_id, record.getId());
            List<SysRoleMenu> menuList = sysRoleMenuService.list(queryWrapper);
            String role_menus = "";
            int a = 0;
            for (SysRoleMenu sysRoleMenu : menuList) {
                a++;
                if (menuList.size() == a) {
                    role_menus += sysRoleMenu.getMenu_id();
                    break;
                }
                role_menus += (sysRoleMenu.getMenu_id() + ",");
            }
            roleDataDto.setRole_menus(role_menus);
            dataDtoList.add(roleDataDto);
        }
        roleDto.setData(dataDtoList);
        roleDto.setCount(pageInfo.getRecords().size());
        roleDto.setCurrentPage((int) pageInfo.getCurrent());
        roleDto.setPageSize((int) pageInfo.getSize());
        roleDto.setTotalPages((int) pageInfo.getTotal());
        return roleDto;
    }

    /**
     * 添加角色数据
     *
     * @param roleAdd
     */
    @Override
    public void add(RoleAdd roleAdd) {
        SysRole sysRole = new SysRole();
        sysRole.setDescription(roleAdd.getDescription());
        sysRole.setName(roleAdd.getName());
//        Date nowDate = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
//        String format = sdf.format(nowDate);
//        sysRole.setCreate_date(LocalDateTime.parse(format));
        sysRole.setCreate_date(LocalDateTime.now());
        // 存储新增的角色信息
        this.save(sysRole);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getName, roleAdd.getName());
        SysRole one = this.list(wrapper).get(0);
        for (String menuid : roleAdd.getMenuids()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRole_id(one.getId());
            sysRoleMenu.setMenu_id(menuid);
            // 将权限信息存入sys_role_menu表中
            sysRoleMenuService.save(sysRoleMenu);
        }
    }

    /**
     * 获取全部角色信息
     *
     * @return
     */
    @Override
    public List<SysRole> getAllData() {
        List<SysRole> allData = this.list();
        return allData;
    }

    @Override
    public RoleInfoDto getRowInfo(String id) {
        return null;
    }

    @Override
    public SysRoleMenuDto rowInfo(String id) {
        SysRoleMenuDto sysRoleMenuDto = new SysRoleMenuDto();
        SysRole sysRole = this.getById(id);
        BeanUtils.copyProperties(sysRole, sysRoleMenuDto);

// 当前角色id对应的菜单权限
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRole_id, id);
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(wrapper);
        List<SysMenu> allMenu = new ArrayList<>();

        for (SysRoleMenu sysRoleMenu : roleMenuList) {
            SysMenu sysMenu = sysMenuService.getById(sysRoleMenu.getMenu_id());
            allMenu.add(sysMenu);
        }

// --------authList----------
// 查询根节点集合
        List<SysMenuDto> rootMenu = new ArrayList<>();
// 遍历所有菜单,查出根节点, pid = 0
        for (SysMenu menu : allMenu) {
            if (menu.getPid() == 0) {
                SysMenuDto sysMenuDto = new SysMenuDto();
                BeanUtils.copyProperties(menu, sysMenuDto);
                rootMenu.add(sysMenuDto);
            }
        }

        // 遍历根节点,为根节点设置子节点,getChild
        for (SysMenuDto menu : rootMenu) {
            List<SysMenuDto> childList = getChild(menu.getId(), allMenu);
            menu.setChildren(childList);
        }
        // --------authList----------
        sysRoleMenuDto.setAuthList(rootMenu);
        return sysRoleMenuDto;
    }

    private List<SysMenuDto> getChild(Integer id, List<SysMenu> allMenu) {
        // 定义子节点集合
        List<SysMenuDto> childList = new ArrayList<>();
        for (SysMenu menu : allMenu) {
            // 如果 传来的id 和 pid 一样,则添加进 childList 中
            if (id.equals(menu.getPid())) {
                SysMenuDto menuDto = new SysMenuDto();
                BeanUtils.copyProperties(menu, menuDto);
                childList.add(menuDto);
            }
        }

        // 如果 childList 大小为0,说明没有子节点,则返回,结束递归
        if (childList.size() == 0) {
            return childList;
        }

        // 不为0,递归
        for (SysMenuDto sysMenuDto : childList) {
            sysMenuDto.setChildren(getChild(sysMenuDto.getId(), allMenu));
        }
        return childList;
    }

    @Override
    public void updateRoleWithMenu(SysRoleMenuDto sysRoleMenuDto) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleMenuDto,sysRole,"create_date","update_date");
// 先修改角色信息
        this.updateById(sysRole);

        List<String> menuids = sysRoleMenuDto.getMenuids();
// 在SysRoleMenu表中先删除角色对应的menuid
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRole_id, sysRoleMenuDto.getId());
        sysRoleMenuService.remove(wrapper);

// 再添加角色对应的menuid
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        for (String menuid : menuids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRole_id(sysRoleMenuDto.getId());
            sysRoleMenu.setMenu_id(menuid);
            sysRoleMenuList.add(sysRoleMenu);
        }
// 批量增加SysRoleMenu 表
        sysRoleMenuService.saveBatch(sysRoleMenuList);
    }

    @Override
    public void delRoleWithMenu(String id) {
        // 1. 删除 role
        this.removeById(id);
// 2. 删除 SysRoleMenu 对应的数据
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRole_id,id);
        sysRoleMenuService.remove(wrapper);
    }

    @Override
    public List<String> getRoleNameList(List<String> roleIdList) {
        List<String> list = new ArrayList<>();
        for (String roleId : roleIdList) {
            SysRole role = this.getById(roleId);
            list.add(role.getName());
        }
        return list;
    }

/*    @Override
    public RoleInfoDto getRowInfo(String id) {
        RoleInfoDto roleInfoDto = new RoleInfoDto();
        SysRole sysRole = this.getById(id);
        BeanUtils.copyProperties(sysRole,roleInfoDto);
        // 获取authList
        List<AuthListDto> authListDtos = new ArrayList<>();
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRole_id,id);
        List<SysRoleMenu> menuList = sysRoleMenuService.list(wrapper);
        for (SysRoleMenu sysRoleMenu : menuList) {
            AuthListDto authListDto = new AuthListDto();
            String menu_id = sysRoleMenu.getMenu_id();
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getPid,menu_id);
            queryWrapper.eq(SysMenu::getIs_show,1);
            SysMenu menu = sysMenuService.getOne(queryWrapper);
            BeanUtils.copyProperties(menu,authListDto);
            // ========================================
            List<AuthListDto> children = new ArrayList<>();
            LambdaQueryWrapper<SysMenu> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysMenu::getIs_show,1).eq(SysMenu::getIs_cache,1);
            List<SysMenu> list = sysMenuService.list(wrapper1);
            for (SysMenu sysMenu : list) {
                AuthListDto authListDto1 = new AuthListDto();
                BeanUtils.copyProperties(sysMenu,authListDto1);

            }
        }

        return roleInfoDto;
    }*/
}
